<template>
    <Dialog
    :visible="exportAllDialogVisible"
    @close="handleExportAllDialogVisible"
    width="80%"
  >
    <ExportTable
      :heads="OrganizationTableHeads"
      :headMap="organizationTableMap"
      :tableData="tableData"
      @moveUp="handleMoveUp"
      @moveDown="handleMoveDown"
    >
    </ExportTable>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleExportAllDialogVisible">取消</el-button>
        <el-button type="primary" @click="handleExportAll">确认导出</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { utils, writeFile } from "xlsx";

import ExportTable from "@/components/ExportTable.vue";
import Dialog from '@/components/common/Dialog.vue';

import { OrganizationTableHeads } from "@/data/tableConfig.ts";
import { organizationTableMap } from "@/data/tableMap.ts";

interface IOrganizationTable {
  organizationName: string;
  organizationProfile: string;
  organizationMemberCount: string;
  organizationPrincipal: string;
  [key: string]: any;
}

const props = defineProps(["exportAllDialogVisible", "tableData"]);
const emits = defineEmits(["closeExportAllDialog"]);

// 事件
const handleMoveUp = (index: number) => {
  [props.tableData[index], props.tableData[index - 1]] = [
    props.tableData[index - 1],
    props.tableData[index],
  ];
};

const handleMoveDown = (index: number) => {
  [props.tableData[index], props.tableData[index + 1]] = [
    props.tableData[index + 1],
    props.tableData[index],
  ];
};

const handleExportAllDialogVisible = () => {
  emits("closeExportAllDialog");
};

const handleExportAll = () => {
  const exportHeads = OrganizationTableHeads.map((head: IObj) => head.value);

  const exportData = [exportHeads];

  for (const item of props.tableData) {
    const rowData: IObj[] = [];

    for (const exportHead of exportHeads) {
      rowData.push(item[organizationTableMap[exportHead]]);
    }

    exportData.push(rowData);
  }

  let ws = utils.aoa_to_sheet(exportData);
  let wb = utils.book_new();
  utils.book_append_sheet(wb, ws, "社团列表"); // 工作簿名称
  writeFile(wb, "社团列表.xlsx"); // 保存的文件名

  handleExportAllDialogVisible();
};
</script>

<style lang="less" scoped>
.myform {
  .top {
    width: 100%;
    display: flex;
    justify-content: space-between;

    :deep(.el-form-item) {
      width: 48%;
    }
  }

  :deep(.el-textarea__inner) {
    height: 100px;
    resize: none;
  }
}
</style>
